package com.aphrodite.ui.graphics;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

import com.aphrodite.image.PackedImage;
import com.aphrodite.util.geom.Rectangle;

/**
 * A compact and simple representation of a Image resource.
 * 
 * @author kentelt
 * 
 */
public class AphroImage {
	private Image image;
	PackedImage packedImage;
	private int x;
	private int y;

	public AphroImage(Image image) {
		this.image = image;
	}

	/**
	 * Renders the given image
	 *<p>
	 * If the image has been packed, the packed image is rendered.
	 *</p>
	 * 
	 * @see AphroImage#packImage()
	 * @param g
	 *            Graphics context
	 * @param anchor
	 *            drawing anchor
	 */
	public void drawImage(Graphics g, int anchor) {
		if (packedImage != null) {
			packedImage.drawImage(g, x, y);
		} else {
			g.drawImage(image, x, y, anchor);
		}
	}

	public Rectangle getBounds() {
		return new Rectangle(x, y, getWidth(), getHeight());
	}

	/**
	 * Get the rgb data of the GraphicsImage
	 * 
	 * @return
	 */
	public int[] getData() {
		return (packedImage != null) ? packedImage.getRGB() : com.aphrodite.image.ImageUtil.getImageRGB(image, image
				.getWidth(), image.getHeight());
	}

	public int getHeight() {
		return (packedImage != null) ? packedImage.getHeight() : image.getHeight();
	}

	public long getSize() {
		int[] dat = getData();
		return dat.length * 4;
	}

	public int getWidth() {
		return (packedImage != null) ? packedImage.getWidth() : image.getWidth();
	}

	/**
	 * Creates a packed image (reduced in size,but slow in rendering) from the
	 * given image instance
	 * <p>
	 * This Operation cannot be undone!. Once an Image is packed the
	 * {@link AphroImage#drawImage} renders the packed image only.
	 * </p>
	 * 
	 * @see com.aphrodite.image.PackedImage
	 */
	public void packImage() {
		packedImage = PackedImage.pack(image);
		image = null;
	}
}
